﻿using DotNetty.Codecs;
using DotNetty.Transport.Channels;
using QQ.Client;
using QQ.Utils;
using System.Collections.Generic;

namespace QQ.Codecs
{
    public class OICQDecoder : MessageToMessageDecoder<Packet.Response.SSOFrame>
    {
        public override bool IsSharable => true;

        private readonly LoginSigInfo loginSigInfo;
        private readonly ECDHHelper ecdhHelper;

        public OICQDecoder(LoginSigInfo loginSigInfo, ECDHHelper ecdhHelper)
        {
            this.loginSigInfo = loginSigInfo;
            this.ecdhHelper = ecdhHelper;
        }

        protected override void Decode(IChannelHandlerContext context, Packet.Response.SSOFrame msg, List<object> output)
        {
            if (msg.commandName == "wtlogin.login")
            {
                var buffer = msg.plainBody;
                Packet.Response.OICQResponse resp = new Packet.Response.OICQResponse()
                {
                    head = buffer.ReadByte(),
                    bodySize = buffer.ReadShort(),
                    protocolVersion = buffer.ReadShort(),
                    commandID = buffer.ReadShort(),
                    unknownConst0x1 = buffer.ReadShort(),
                    uin = buffer.ReadInt(),
                    encryptionMethod = buffer.ReadShort(),
                    unknownConst0x0 = buffer.ReadByte()
                };
                if (resp.encryptionMethod == 0)
                {
                    resp.plainBody = QQTea.Decrypt(buffer.ReadBytes(buffer.ReadableBytes - 1).ToArray(), ecdhHelper.getSharedKey()).ToByteBuffer();
                    System.Console.WriteLine($"解密OICQ成功，{nameof(resp.uin)}={resp.uin}");
                    loginSigInfo.uin = (uint)resp.uin;
                }
                else
                {
                    throw new System.Exception($"{nameof(resp.encryptionMethod)}不支持，还没写代码");
                }
                output.Add(resp);
            }
            else output.Add(msg);
        }
    }
}
